package com.fan89.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fan89.common.lang.Result;
import com.fan89.dto.LoginDto;
import com.fan89.dto.PasswordDto;
import com.fan89.dto.RegisterDto;
import com.fan89.entity.User;
import com.fan89.service.UserService;
import com.fan89.util.CheckUtil;
import com.fan89.util.JwtUtils;
import com.fan89.util.MD5Utils;
import com.fan89.util.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Random;

/**
 * 用户登录接口
 * @author lx909
 */
@Api(value = "账号管理api",tags = "账号管理相关接口")
@RestController
public class AccountController {

    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;

    @Value("${baseUrl}")
    private String baseUrl;

    /**
     * 登录
     *
     * @param loginDto
     * @param response
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {

        //判断用户是否存在
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user, "账号不存在");

        //判断密码是否正确
        if (user == null || !user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
            return Result.error("账号或密码错误");
        }

        //根据用户id生成jwt
        String jwt = jwtUtils.generateToken(user.getId());
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");

        //返回用户信息
        return Result.success("登录成功", MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .map()
        );
    }

    @ApiOperation("修改密码")
    @PostMapping("/changePassword")
    public Result changePassword(@Validated @RequestBody PasswordDto passwordDto, HttpServletResponse response) {

        Long currentUserId = ShiroUtils.getProfile().getId().longValue();
        if (currentUserId == null) {
            return Result.error("请先登录");
        } else {

            User user = userService.getOne(new QueryWrapper<User>().eq("id", currentUserId));
            if (!user.getPassword().equals(SecureUtil.md5(passwordDto.getPassword()))) {
                return Result.error("账号或密码错误");
            }
            if (!passwordDto.getPassword1().equals(passwordDto.getPassword2()) ) {
                return Result.error("两次输入的密码不相同");
            }
            user.setPassword(MD5Utils.code(passwordDto.getPassword2()));
            userService.saveOrUpdate(user);

            //根据用户id生成jwt
            String jwt = jwtUtils.generateToken(user.getId());
            response.setHeader("Authorization", jwt);
            response.setHeader("Access-control-Expose-Headers", "Authorization");

            //返回用户信息
            return Result.success("登录成功", MapUtil.builder()
                    .put("id", user.getId())
                    .put("username", user.getUsername())
                    .put("avatar", user.getAvatar())
                    .put("email", user.getEmail())
                    .map()
            );

        }
    }

    /**
     * 注册
     *
     * @param
     * @param response
     * @return
     */
    @ApiOperation("注册")
    @PostMapping("/register")
    public Result register(@Validated @RequestBody RegisterDto registerDto, HttpServletResponse response) {
CheckUtil.isEmail("");

        if (!CheckUtil.isEmail(registerDto.getEmail())) {
            return Result.error("邮箱格式不正确");
        }
        //判断用户是否存在
        User user1 = userService.getOne(new QueryWrapper<User>().eq("username", registerDto.getUsername()));
        User user2 = userService.getOne(new QueryWrapper<User>().eq("email", registerDto.getEmail()));
        if (user1 != null) {
            return Result.error("该用户名已存在");
        }
        if (user2 != null) {
            return Result.error("该邮箱已存在");
        }
        Random random = new Random();
        Integer result = random.nextInt(5);
        Integer randomAvatar = result + 1;

        User userNew = new User();
        MD5Utils md5Utils = new MD5Utils();
        userNew.setEmail(registerDto.getEmail());
        userNew.setUsername(registerDto.getUsername());
        userNew.setPassword(md5Utils.code(registerDto.getPassword()));
        userNew.setStatus(0);
        userNew.setUserType("USER");
        userNew.setNickname(registerDto.getNickname());
        userNew.setAvatar(baseUrl + "/img/avatar/" + randomAvatar.toString() + ".jpg");
        userService.save(userNew);

        //返回用户信息
        return Result.success("注册用户成功");
    }

    /**
     * 注销
     *
     * @return
     */
    @ApiOperation("退出登录")
    @RequiresAuthentication //登录后才能访问该接口
    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.success("注销成功");
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/getUserInfo")
    public Result getUserInfo(@Validated HttpServletResponse response) {
        Object obj=null;
        Long currentUserId = ShiroUtils.getProfile().getId().longValue();
        String userName = ShiroUtils.getProfile().getUsername();
        if (userName == null) {
            return Result.error("无登录用户");
        }
        //判断用户是否存在
        User user = userService.getOne(new QueryWrapper<User>().eq("username", userName));
        Assert.notNull(user, "账号不存在");

        //返回用户信息
        return Result.success("登录成功", MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .map()
        );
    }
}
